import random

from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView

from .models import User
from .serializers import UserModelSerializer
from .utils import get_user_by_account


class UserAPIView(CreateAPIView):
    """用户信息视图"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


"""
GET /user/mobile/<mobile>/
"""
import re
from rest_framework import status


class MobileAPIView(APIView):
    def get(self, request, mobile):
        if not re.match(r"^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$", mobile):
            return Response({"message": "手机号码格式有误！"}, status=status.HTTP_400_BAD_REQUEST)

        ret = get_user_by_account(mobile)
        if ret is not None:
            return Response({"message": "手机号已被注册！"}, status=status.HTTP_400_BAD_REQUEST)

        return Response({"message": "ok！"})


import random
from django_redis import get_redis_connection
from luffyapi.settings import constants
from luffyapi.libs.yuntongxun.sms import CCP
import logging
log = logging.getLogger("django")


class SMSAPIView(APIView):
    def get(self, request, mobile):
        """短信发送"""
        # 1.验证手机号码是否在60秒内曾经发送过短信
        redis_conn = get_redis_connection("sms_code")
        ret = redis_conn.get("mobile_%s" % mobile)
        if ret is not None:
            return Response({"message": "60秒内已发送过短信，勿重复发送！"}, status=status.HTTP_400_BAD_REQUEST)

        # 2.生成短信验证码
        sms_code = "%06d" % random.randint(1, 999999)

        # 3.保存短信验证码到redis[使用事务把多条命令集中发送给redis]
        pipe = redis_conn.pipeline()
        # 开启事务 [无法管理数据库的读取数据操作]
        pipe.multi()
        # 把事务中要完成的所有操作写入到管道中
        pipe.setex("sms_%s" % mobile, constants.SMS_EXPIRE_TIME, sms_code)
        pipe.setex("mobile_%s" % mobile, constants.SMS_INTERVAL_TIME, "_")
        # 执行事务
        pipe.execute()

        # 4.调用短信sdk发送短信
        try:
            ccp = CCP()
            ccp.send_template_sms(mobile, [sms_code, constants.SMS_EXPIRE_TIME // 60], constants.SMS_TEMPLATE_ID)
            # if not ret:
            #     log.error("注册短信发送失败！手机号：%s" % mobile)
            #     return Response({"message": "发送短信失败！"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        except:
            return Response({"message": "发送短信失败！"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 5.响应发送短信的结果
        return Response({"message": "发送短信成功！"})
